<?php
	class UnitController extends Controller
	{
		public function actionAddUnit()
		{
			$id_u = Yii::app()->user->getId();
			$id_sett = User::model()->findByPk($id_u)->current_settlement;
			
			$res = UnitType::model()->findByPk($_POST['Type'])->resources;
			$res_arr = explode(":", $res);
			$res_count = Resources::model()->findAll("id_settlement = " . $id_sett . " and id_resource = " . $res_arr[0]);
		
			if($res_arr[1]*$_POST['Count'] > $res_count[0]->count)
			{
				Yii::app()->user->setFlash('error', 'Недостаточно ресурсов');
				$this->redirect($this->createUrl('building/building', array('id' => $_POST['id_build'])));
			}
			
			$res_count[0]->count -= $res_arr[1]*$_POST['Count'];
			$res_count[0]->save();
			
			$c = Yii::app()->db;
			$sql = "INSERT INTO `units` (id_unit, id_user, id_owner, id_settlement, lvl) VALUES";
			
			for($i = 0; $i < $_POST['Count']; $i++)
			{
				$sql .= " (" . $_POST['Type'] . ", " . $id_u  . ", " . $id_sett . ", " . $id_sett . ", " . "1) ,";
			}
			
			$sql = rtrim($sql, ",");
			$com = $c->createCommand($sql);
			$com->execute();
			
			$this->redirect($this->createUrl('field/fields'));
		}
	}
?>